package com.lwq.util;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/6/20
 */
@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    public static final String UNREADED = "UNREAD:";

    public void put(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeTransactionSupport();
        }
    }

    public void put(String key, String value, long timeout, TimeUnit unit) {
        try {
            stringRedisTemplate.opsForValue().set(key, value, timeout, unit);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeTransactionSupport();
        }
    }

    public <T> void put(final String key, final T value){
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功；false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> void setCacheList(final String key, final List<T> dataList)
    {
        if(dataList == null || dataList.isEmpty()){
            return ;
        }
        redisTemplate.opsForValue().set(key, JSON.toJSONString(dataList));
        return ;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key, Class<T> clz)
    {
        return redisTemplate.opsForValue().get(key) == null ?
                new ArrayList<>() : JSON.parseArray(redisTemplate.opsForValue().get(key).toString(), clz);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    public String get(String key) {
        try {
            return stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeTransactionSupport();
        }
        return null;
    }

    public Set<String> getKeys(String pattern) {
        try {
            return stringRedisTemplate.keys(pattern);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeTransactionSupport();
        }
        return null;
    }

    public void del(String key) {
        try {
            stringRedisTemplate.delete(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeTransactionSupport();
        }
    }

    public void dels(Collection<String> keys) {
        try {
            stringRedisTemplate.delete(keys);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeTransactionSupport();
        }
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
    {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    public Long removeSet(final String key, Object... values){
        return redisTemplate.opsForSet().remove(key,values);
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }


    public void send(String channel, String msg) {
        try {
            stringRedisTemplate.convertAndSend(channel, msg);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeTransactionSupport();
        }
    }

    public Long increment(String key, Integer self) {
        Long increment = getStringRedisTemplate().opsForValue().increment(key, self);
        if (increment == Long.MAX_VALUE) {
            del(key);
            increment = getStringRedisTemplate().opsForValue().increment(key, self);
        }
        return increment;
    }

    public StringRedisTemplate getStringRedisTemplate() {
        return stringRedisTemplate;
    }

    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    private void closeTransactionSupport() {
        RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
    }

}
